package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import org.apache.commons.io.FilenameUtils;//
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * @Author: lx
 * @Time: 9:17
 * @Description:
 */
@RestController
@RequestMapping("admin/product")
public class UploadFileController {


    @Value("${img.url}")
    private String imgUrl;

    //上传图片
    //  @RequestParam  ==     byte[] files  =   request.getParamter(files);
    // http://localhsot:8089/admin/product/fileUpload   POST
      // 请求体中  files=bia...二进制的图片 files=二进制图片
    @PostMapping("/fileUpload")
    //public Result fileUpload(@RequestParam MultipartFile[] files){//发生 批量上传  请求一次  上传10张图片
    public Result fileUpload(MultipartFile file) throws Exception{

        System.out.println(file.getSize());
        System.out.println(file.getName());//file  Form Data Key值
        //file.getBytes()
        System.out.println(file.getOriginalFilename());//324532454gsgfsadfw.jpg
        //扩展名
        String ext = FilenameUtils.getExtension(file.getOriginalFilename());


        String path = ClassUtils.getDefaultClassLoader()
                .getResource("fdfs_client.conf").getPath();
        //流：只能读取绝对路径  不认识相对路径
        ClientGlobal.init(path);
        //2:上传连接请求  找跟踪器
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        //3:连接存储节点Storage
        StorageClient1 storageClient1 = new StorageClient1(trackerServer,null);
        //4:上传图片
        String file_id = storageClient1.upload_file1(file.getBytes()
                , ext, null);
        System.out.println("http://192.168.200.128:8080/" +file_id);
        return Result.ok(imgUrl +file_id);//硬编码问题
    }
}
